import os
import pymysql
from datetime import datetime as datetime
from flask import Flask,render_template,Response,request
from tornado.httpserver import HTTPServer
from tornado.wsgi import WSGIContainer
from tornado.ioloop import IOLoop

from pyecharts.charts import Bar,Line
from pyecharts import options as opts
from pyecharts.charts import Bar3D
from pyecharts.faker import Faker

import sys
import json
import random


mypath = os.path.dirname(os.path.abspath(sys.argv[0]))

template_folder = os.path.join(mypath, 'templates')
static_folder = os.path.join(mypath, 'static')

app = Flask(__name__, template_folder=template_folder, static_folder=static_folder)



class mysql():
    def __init__(self):
        self.conn = pymysql.connect(
            host="localhost",
            port=3306,
            user="root",
            password="anjiu123",
            database="anjiu",
            charset="utf8")
        self.cur = self.conn.cursor()

    def get_bar_base(self,model):
        try:
            time_day = str(datetime.today())[:10]
            if model == 5:
                sql = "select * from bar_base where time='{}'".format(time_day)
            else:
                sql = "select * from bar_base where time='{}' and model={}".format(time_day,model)
            self.cur.execute(sql)
            return self.cur.fetchall()
        except Exception as e:
            self.conn.rollback()
            return False

    def get_line_base(self,name_line=None):
        try:
            time_day = str(datetime.today())[:10]
            if name_line:
                sql = "select * from line_base where name='{}' and model=1".format(name_line)
            else:
                sql = "select * from line_base"
            self.cur.execute(sql)
            return self.cur.fetchall()
        except Exception as e:
            self.conn.rollback()
            return False

    def closesql(self):
        self.cur.close()
        self.conn.close()


mymysql = mysql()


@app.route("/bar",methods=['GET','POST'])
def bar_table():
    return render_template("bar.html")


@app.route("/line",methods=['GET','POST'])
def line_table():
    return render_template("line.html")


@app.route("/bard",methods=['GET','POST'])
def bar3d_table():
    return render_template("bard.html")


@app.route("/",methods=['GET','POST'])
def index():
    return render_template("bar.html")


@app.route("/lineChart")
def get_line_chars():
    c = line_base()
    if c:
        return c.dump_options_with_quotes()
    return {"data":"null"}


@app.route("/bardChart")
def get_bar3d_chars():
    c = bar_3d()
    if c:
        return c.dump_options_with_quotes()
    return {"data":"null"}


@app.route("/barChart")
def get_bar_chart():
    n = request.args.get("name")
    c = bar_base(int(n))
    if c:
        return c.dump_options_with_quotes()
    return {"data":"null"}


def line_base():
    game = mymysql.get_bar_base(1)
    if game:
        time_line = mymysql.get_line_base(name_line=game[0][1])
        if time_line:
            c = (
                Line()
                .add_xaxis([line_[2] for line_ in time_line])
                .set_global_opts(title_opts=opts.TitleOpts(title="新增监控", subtitle=str(datetime.today())[:10]),
                xaxis_opts=opts.AxisOpts(is_show=True))
            )
            for name in game:
                c.add_yaxis(name[1], [im[0] for im in mymysql.get_line_base(name[1])])
            return c
    return None


def bar_base(n):
    game = mymysql.get_bar_base(n)
    if n == 1:
        mytitle = "新增"
    elif n == 2:
        mytitle = "留存成功"
    elif n == 3:
        mytitle = "留存失败"
    elif n == 4:
        mytitle = "消费"
    if game:
        c = (
            Bar()
            .add_xaxis([name[1] for name in game])
            .add_yaxis(mytitle, [m[0] for m in game], color=Faker.rand_color())
            .set_global_opts(
            title_opts=opts.TitleOpts(title=mytitle),
            axispointer_opts=opts.AxisPointerOpts(is_show=True),
            xaxis_opts=opts.AxisOpts(is_show=False),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")])
        )
        return c
    return None


def bar_3d():
    game = mymysql.get_bar_base(5)
    if game:
        y_axis = {"1":"新增","2":"留存成功","3":"留存失败","4":"消费"}
        mydic = {}
        for me in game:
            if me[1] not in mydic:
                mydic.update({me[1]:{str(me[3]):me[0]}})
            else:
                mydic[me[1]].update({str(me[3]):me[0]})

        gamelist = list(mydic)
        modelist = [y_axis[i] for i in y_axis]

        bar_3d = Bar3D()
        mymax = 0
        sum_ = 0
        for name in mydic:
            for model in mydic[name]:
                if mymax < int(mydic[name][model]):
                    mymax = int(mydic[name][model])
                bar_3d.add(
                series_name=name,
                data=[(sum_,(int(model)-1),int(mydic[name][model]))],
                shading="lambert",
                xaxis3d_opts=opts.Axis3DOpts(type_="category",data=gamelist),
                yaxis3d_opts=opts.Axis3DOpts(type_="category",data=modelist),
                zaxis3d_opts=opts.Axis3DOpts(type_="value"),
            )
            sum_ += 1
        bar_3d.set_global_opts(
        visualmap_opts=opts.VisualMapOpts(max_=mymax),
        title_opts=opts.TitleOpts(title="游戏监控-3d图"))
        c = ( bar_3d )
        return c
    return None



if __name__ == "__main__":
    s = HTTPServer(WSGIContainer(app))
    s.listen(9000)
    IOLoop.current().start()